from flask import Blueprint, render_template, request
from module_admin.entity.do.base import db
from module_admin.entity.do.content import CourseContent
from module_admin.entity.do.course import Course
from module_admin.utils.http import fail_api, success_api, table_api
from module_admin.utils.validate import str_escape

course = Blueprint('course', __name__)


@course.route('/course', methods=['GET'])
def get_course():
    if request.method == 'GET':
        return render_template('Course.html')


@course.route('/course/management', methods=['GET'])
def get_course_management():
    if request.method == 'GET':
        return render_template('CourseManagement.html')


@course.post('/add_course')
def add_course():
    req_json = request.get_json(force=True)
    course_name = str_escape(req_json.get('name'))
    description = str_escape(req_json.get('description'))

    if not course_name:
        return fail_api(msg="课程名称不得为空")

    course = Course(name=course_name, description=description)
    db.session.add(course)
    db.session.commit()
    return success_api(msg="课程添加成功")


@course.get('/course_list')
def get_all_courses():
    # 查询所有课程
    courses = Course.query.all()

    # 构建返回数据
    course_list = [
        {
            "id": course.id,
            "name": course.name,
            "description": course.description,
        }
        for course in courses
    ]

    return table_api(data=course_list, msg="获取成功")


@course.post('/edit_course')
def edit_course():
    req_json = request.get_json(force=True)
    id = req_json.get('id')
    new_name = str_escape(req_json.get('name'))
    new_description = str_escape(req_json.get('description'))

    # 查找指定课程
    course = Course.query.filter_by(id=id).first()

    if not course:
        return fail_api(msg="课程不存在")

    # 更新课程信息
    if new_name:
        course.name = new_name
    if new_description:
        course.description = new_description

    db.session.commit()
    return success_api(msg="课程编辑成功")


@course.get('/delete_course/<int:course_id>')
def delete_course(course_id):
    # 查找指定课程
    course = Course.query.filter_by(id=course_id).first()

    if not course:
        return fail_api(msg="课程不存在")

    # 删除课程内容的关联
    CourseContent.query.filter_by(course_id=course.id).delete()  # 假设content_id是与内容关联的字段

    # 删除课程
    db.session.delete(course)
    db.session.commit()

    return success_api(msg="课程删除成功")
